Python Basic CheatSheet

Python File

define coding and python interpreter at the top of the file


In [19]:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# -*- coding: latin1 -*-
# -*- coding: iso-8859-1 -*-
# durch coding auch umlaut möglich

Asking for Help


In [8]:
help(str)


Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(...)
 |      S.__format__(format_spec) -> str
 |      
 |      Return a formatted version of S as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(...)
 |      S.capitalize() -> str
 |      
 |      Return a capitalized version of S, i.e. make the first character
 |      have upper case and the rest lower case.
 |  
 |  casefold(...)
 |      S.casefold() -> str
 |      
 |      Return a version of S suitable for caseless comparisons.
 |  
 |  center(...)
 |      S.center(width[, fillchar]) -> str
 |      
 |      Return S centered in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |  
 |  encode(...)
 |      S.encode(encoding='utf-8', errors='strict') -> bytes
 |      
 |      Encode S using the codec registered for encoding. Default encoding
 |      is 'utf-8'. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 |      'xmlcharrefreplace' as well as any other name registered with
 |      codecs.register_error that can handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(...)
 |      S.expandtabs(tabsize=8) -> str
 |      
 |      Return a copy of S where all tab characters are expanded using spaces.
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found, 
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  isalnum(...)
 |      S.isalnum() -> bool
 |      
 |      Return True if all characters in S are alphanumeric
 |      and there is at least one character in S, False otherwise.
 |  
 |  isalpha(...)
 |      S.isalpha() -> bool
 |      
 |      Return True if all characters in S are alphabetic
 |      and there is at least one character in S, False otherwise.
 |  
 |  isdecimal(...)
 |      S.isdecimal() -> bool
 |      
 |      Return True if there are only decimal characters in S,
 |      False otherwise.
 |  
 |  isdigit(...)
 |      S.isdigit() -> bool
 |      
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
 |  
 |  isidentifier(...)
 |      S.isidentifier() -> bool
 |      
 |      Return True if S is a valid identifier according
 |      to the language definition.
 |      
 |      Use keyword.iskeyword() to test for reserved identifiers
 |      such as "def" and "class".
 |  
 |  islower(...)
 |      S.islower() -> bool
 |      
 |      Return True if all cased characters in S are lowercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  isnumeric(...)
 |      S.isnumeric() -> bool
 |      
 |      Return True if there are only numeric characters in S,
 |      False otherwise.
 |  
 |  isprintable(...)
 |      S.isprintable() -> bool
 |      
 |      Return True if all characters in S are considered
 |      printable in repr() or S is empty, False otherwise.
 |  
 |  isspace(...)
 |      S.isspace() -> bool
 |      
 |      Return True if all characters in S are whitespace
 |      and there is at least one character in S, False otherwise.
 |  
 |  istitle(...)
 |      S.istitle() -> bool
 |      
 |      Return True if S is a titlecased string and there is at least one
 |      character in S, i.e. upper- and titlecase characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |      Return False otherwise.
 |  
 |  isupper(...)
 |      S.isupper() -> bool
 |      
 |      Return True if all cased characters in S are uppercase and there is
 |      at least one cased character in S, False otherwise.
 |  
 |  join(...)
 |      S.join(iterable) -> str
 |      
 |      Return a string which is the concatenation of the strings in the
 |      iterable.  The separator between elements is S.
 |  
 |  ljust(...)
 |      S.ljust(width[, fillchar]) -> str
 |      
 |      Return S left-justified in a Unicode string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  lower(...)
 |      S.lower() -> str
 |      
 |      Return a copy of the string S converted to lowercase.
 |  
 |  lstrip(...)
 |      S.lstrip([chars]) -> str
 |      
 |      Return a copy of the string S with leading whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  partition(...)
 |      S.partition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, and return the part before it,
 |      the separator itself, and the part after it.  If the separator is not
 |      found, return S and two empty strings.
 |  
 |  replace(...)
 |      S.replace(old, new[, count]) -> str
 |      
 |      Return a copy of S with all occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  rjust(...)
 |      S.rjust(width[, fillchar]) -> str
 |      
 |      Return S right-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |      
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |  
 |  rsplit(...)
 |      S.rsplit(sep=None, maxsplit=-1) -> list of strings
 |      
 |      Return a list of the words in S, using sep as the
 |      delimiter string, starting at the end of the string and
 |      working to the front.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified, any whitespace string
 |      is a separator.
 |  
 |  rstrip(...)
 |      S.rstrip([chars]) -> str
 |      
 |      Return a copy of the string S with trailing whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  split(...)
 |      S.split(sep=None, maxsplit=-1) -> list of strings
 |      
 |      Return a list of the words in S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator and empty strings are
 |      removed from the result.
 |  
 |  splitlines(...)
 |      S.splitlines([keepends]) -> list of strings
 |      
 |      Return a list of the lines in S, breaking at line boundaries.
 |      Line breaks are not included in the resulting list unless keepends
 |      is given and true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(...)
 |      S.strip([chars]) -> str
 |      
 |      Return a copy of the string S with leading and trailing
 |      whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  swapcase(...)
 |      S.swapcase() -> str
 |      
 |      Return a copy of S with uppercase characters converted to lowercase
 |      and vice versa.
 |  
 |  title(...)
 |      S.title() -> str
 |      
 |      Return a titlecased version of S, i.e. words start with title case
 |      characters, all remaining cased characters have lower case.
 |  
 |  translate(...)
 |      S.translate(table) -> str
 |      
 |      Return a copy of the string S in which each character has been mapped
 |      through the given translation table. The table must implement
 |      lookup/indexing via __getitem__, for instance a dictionary or list,
 |      mapping Unicode ordinals to Unicode ordinals, strings, or None. If
 |      this operation raises LookupError, the character is left untouched.
 |      Characters mapped to None are deleted.
 |  
 |  upper(...)
 |      S.upper() -> str
 |      
 |      Return a copy of S converted to uppercase.
 |  
 |  zfill(...)
 |      S.zfill(width) -> str
 |      
 |      Pad a numeric string S with zeros on the left, to fill a field
 |      of the specified width. The string S is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  maketrans(x, y=None, z=None, /)
 |      Return a translation table usable for str.translate().
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.

Import

import <modulname>
<modulname>.<modulfunction>

from <modulname> import <function>
<function>

In [20]:
import math
math.sqrt(25)
     
from math import sqrt
sqrt(25)
     
from math import *
sqrt(25)
log(10)

import numpy
import numpy as np

Variables and DataTypes

Variable Assigments


In [21]:
var_int = 5
var_long = 1.23
var_float = 9.25e-3
var_complex = (5.3 + 3j)
var_bool = True

Calculation with Variables


In [23]:
ans = x+2  # Sum of two variables
ans = x-2  # Subtraction of two variables
ans = x*2  # Multiplication of two variables
ans = x**2 # Exponentiation of a variable
ans = x%2  # Remainder of a variable
x/float(2) # Division of a variable


Out[23]:
2.5

Types and Type Conversions


In [18]:
int()               # to integer
float()             # to float
complex()           # to complex
long()              # to long
unichr()            # int to 1 char
ord()               # 1 element string to int
str()               # int to string
bool()              # to boolean


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-d3e7cc41c641> in <module>()
      2 float()             # to float
      3 complex()           # to complex
----> 4 long()              # to long
      5 unichr()            # int to 1 char
      6 ord()               # 1 element string to int

NameError: name 'long' is not defined

Strings


In [24]:
oneline_string_1 = 'String'
oneline_string_2 = "String"
multiline_string = '''Multiline String
on multiple lines'''

String Operations


In [26]:
my_string = "Awesome String"
ans = my_string * 2
print(ans)
ans = my_string + ' Add'
print(ans)
ans = 'm' in my_string
print(ans)
# index starts at 0
ans = my_string[3]
print(ans)
ans = my_string[4:9]
print(ans)


Awesome StringAwesome String
Awesome String Add
True
s
ome S

String Methodes


In [12]:
ans = my_string.upper()             # String to uppercase
print(ans)
ans = my_string.lower()             # String to lowercase
print(ans)
ans = my_string.count('w')          # Count String elements
print(ans)
ans = my_string.replace('e', 'i')   # Replace String elements
print(ans)
ans = my_string.strip()             # Strip whitespaces
print(ans)


THISSTRINGISAWESOME
thisstringisawesome
1
thisStringIsAwisomi
thisStringIsAwesome

Lists


In [28]:
>>> a = 'is'
>>> b = 'nice'
>>> my_list = ['my', 'list', a, b]
>>> my_list2 = [[4,5,6,7], [3,4,5,6]]

Selecting List Elements


In [31]:
# Subset
my_list[1]      # Select item at index 1
my_list[-3]     # Select 3rd last item
# Slice
my_list[1:3]    # Select item at index 1 and 2
my_list[1:]     # Select items after index 0
my_list[:3]     # Select items before index 3
my_list[:]      # Copy my_list
# Subset Lists of Lists
my_list2[1][0]  # my_list[list][itemOfList]
my_list2[1][:2] #


Out[31]:
[3, 4]

List Operations


In [ ]:
my_list + my_list
my_list* 2
my_list2 > 4

List Methods


In [39]:
my_list.index(a)      # Get the index of an item
my_list.count(a)      # Count an item
my_list.append("!")   # Append an item at a time
my_list.reverse()     # Reverse tbe list
my_list.extend("!")   # Append an item
my_list.sort()        # Sort the list
my_list.insert(0,"!") # Insert an item
my_list.pop(-1)       # Remove an item
my_list.remove('!')   # Remove an item
del(my_list[0:1])     # Remove an item

Numpy Arrays


In [41]:
my_list = [1, 2, 3, 4]
my_array = np.array(my_list)
my_2darray = np.array([[1,2,3],[4,5,6]])

Selecting Numpy Array Elements


In [45]:
# Subset
my_array[1]     # Select item at index 1

# Slice
my_array[0:2]   # Select items at index 0 and 1

# Subset 2D Numpy arrays
my_2darray[:,0]  # my_2darray[rows, columns]


Out[45]:
array([1, 4])

Numpy Array Operations


In [47]:
my_array > 3                   # array([False, False, False, True])
my_array * 2                   # array([2,4,6,8])
my_array + np.array([5,6,7,8]) # array([6,8,10,12])


Out[47]:
array([ 6,  8, 10, 12])

Numpy Array Functions


In [57]:
my_array.shape            # Get the dimensions of the array
np.append(my_array, np.array([5,6,7,8]))  # Append items to an array
np.insert(my_array, 1, 5) # Insert items in an array
np.delete(my_array,[1])   # Delete items in an array
np.mean(my_array)         # Mean of the array
np.median(my_array)       # Median of the array
np.corrcoef(my_array)     # Correlation coefficient
np.std(my_array)          # Standart deviation


Out[57]:
1.118033988749895

Operator Priority


In [ ]:
+                   # Plus         3 + 5 = 8 'a' + 'b' = 'ab'
-                   # Minus        -5.2 order 5 - 2
*                   # Multiplcation 2 * 3 = 6
**                  # Power        3 ** 4 = 3 * 3 * 3 * 3 = 81
/                   # Division     4 / 3 = 1 oder 4.0/3 = 1.3333...
//                  # Integer  Division 4 // 3.0 = 1.0
%                   # Modulo       8 % 3 = 2
<<                  # Bitwise left 2 << 2 = 8   (in binary)
>>                  # Bitwise right 11 >> 1 = 5 (in binary)
&                   # Bitwise AND  5 & 3 = 1    (in binary)
¦                   # Bitwise OR   5 | 3 = 7    (in binary)
^                   # Bitwise XOR  5 ^ 3 = 6    (in binary)
~                   # Bitwise NOT  ~5 = -6
<                   # Smaller as
>                   # Bigger as
<=                  # Smaller Equal
>=                  # Bigger Equal
==                  # Equal
!=                  # Not Equal
not                 # log NOT
and                 # log AND
or                  # log OR

In [ ]: